#!/usr/bin/env python3
"""
精确分析Key Features的DOM结构和滚动影响
专门针对单个车型的Key Features进行测试
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
import time
import json

def analyze_key_features_dom():
    """精确分析Key Features的DOM结构"""
    
    # Chrome设置
    chrome_options = Options()
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--window-size=1920,1080')
    # chrome_options.add_argument('--headless')  # 注释掉以便观察
    
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=chrome_options)
    
    try:
        print("🔍 精确分析Key Features的DOM结构...")
        
        # 访问页面
        url = "https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2/model?catalogId=WAEGB-CGE-2022-FocusMCAGBR202450&series=ACMAA_VS-DH&planId=c"
        print(f"🌐 访问页面: {url}")
        driver.get(url)
        
        # 等待页面加载
        print("⏳ 等待页面加载...")
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, 'div[data-cy][class*="ProductTile"]'))
        )
        
        # 处理Cookie同意
        try:
            cookie_buttons = driver.find_elements(By.CSS_SELECTOR, 'button[id*="cookie"], button[class*="cookie"], button[data-cy*="cookie"], button[class*="consent"]')
            for btn in cookie_buttons:
                if btn.is_displayed():
                    btn.click()
                    time.sleep(1)
        except:
            pass
        
        print("🎯 寻找Titanium车型...")
        
        # 找到Titanium车型
        titanium_element = None
        max_attempts = 5
        for attempt in range(max_attempts):
            try:
                elements = driver.find_elements(By.CSS_SELECTOR, 'div[data-cy][class*="ProductTile"]')
                print(f"第{attempt+1}次尝试，找到 {len(elements)} 个车型元素")
                
                for element in elements:
                    data_cy = element.get_attribute('data-cy')
                    if data_cy and 'titanium' in data_cy.lower():
                        titanium_element = element
                        print(f"✅ 找到Titanium元素: data-cy='{data_cy}'")
                        break
                
                if titanium_element:
                    break
                    
                # 如果没找到，尝试点击下一页
                try:
                    next_btn = driver.find_element(By.CSS_SELECTOR, 'button[aria-label*="next"], button[action="next"]')
                    if next_btn.is_displayed():
                        next_btn.click()
                        time.sleep(2)
                except:
                    break
                    
            except Exception as e:
                print(f"尝试 {attempt+1} 失败: {e}")
                time.sleep(1)
        
        if not titanium_element:
            print("❌ 未找到Titanium车型")
            return
        
        print("🔍 找到View Specifications按钮...")
        
        # 找到并点击View Specifications按钮
        try:
            # 悬停到元素上
            ActionChains(driver).move_to_element(titanium_element).perform()
            time.sleep(1)
            
            # 查找按钮
            spec_button = titanium_element.find_element(By.CSS_SELECTOR, 'button[data-cy="product-tile-overlay"]')
            print("✅ 找到View Specifications按钮")
            
            # 点击按钮
            driver.execute_script("arguments[0].click();", spec_button)
            print("✅ 成功点击按钮")
            
            # 等待模态框出现
            time.sleep(3)
            
        except Exception as e:
            print(f"❌ 点击按钮失败: {e}")
            return
        
        # 分析DOM结构
        print("\n🔍 分析当前页面的DOM结构...")
        
        def analyze_dom_structure():
            """分析DOM结构，找到Key Features的确切位置"""
            
            # 查找所有可能包含Key Features的容器
            containers = []
            
            # 尝试多种可能的容器选择器
            container_selectors = [
                'div[role="dialog"]',
                'div[class*="Modal"]',
                'div[class*="ProductTile"]',
                'div[class*="Overlay"]',
                'div[class*="Popup"]'
            ]
            
            for selector in container_selectors:
                try:
                    elements = driver.find_elements(By.CSS_SELECTOR, selector)
                    if elements:
                        print(f"选择器 '{selector}' 找到 {len(elements)} 个容器")
                        containers.extend(elements)
                except:
                    continue
            
            # 查找包含"Key Features"文本的元素
            key_feature_headers = []
            try:
                # 查找包含"Key Features"的标题
                headers = driver.find_elements(By.XPATH, "//*[contains(text(), 'Key Features')]")
                print(f"找到 {len(headers)} 个包含'Key Features'的元素")
                key_feature_headers = headers
            except:
                pass
            
            # 分析每个Key Features部分
            results = []
            
            for i, header in enumerate(key_feature_headers):
                print(f"\n分析第 {i+1} 个Key Features部分:")
                print(f"  标题文本: {header.text}")
                print(f"  标签名: {header.tag_name}")
                print(f"  class: {header.get_attribute('class')}")
                
                # 查找该标题后的列表
                try:
                    # 尝试找到紧跟在标题后的ul元素
                    parent = header.find_element(By.XPATH, "./..")
                    lists = parent.find_elements(By.CSS_SELECTOR, "ul")
                    
                    for j, ul in enumerate(lists):
                        print(f"    列表 {j+1}:")
                        print(f"      class: {ul.get_attribute('class')}")
                        
                        # 获取该列表中的li元素
                        lis = ul.find_elements(By.CSS_SELECTOR, "li")
                        print(f"      包含 {len(lis)} 个li元素")
                        
                        features = []
                        for k, li in enumerate(lis):
                            text = li.text.strip()
                            if text:
                                features.append(text)
                                if k < 5:  # 只显示前5个
                                    print(f"        {k+1}. {text}")
                        
                        results.append({
                            'header_text': header.text,
                            'list_index': j,
                            'list_class': ul.get_attribute('class'),
                            'features_count': len(features),
                            'features': features
                        })
                        
                except Exception as e:
                    print(f"    查找列表失败: {e}")
            
            return results
        
        # 不滚动时的分析
        print("\n📊 不滚动时的DOM分析:")
        initial_analysis = analyze_dom_structure()
        
        # 滚动操作
        print("\n📊 开始滚动操作...")
        try:
            # 查找模态框或主要容器
            modal = driver.find_element(By.CSS_SELECTOR, 'div[role="dialog"], div[class*="Modal"]')
            
            # 获取容器的初始高度和滚动高度
            initial_scroll_height = driver.execute_script("return arguments[0].scrollHeight", modal)
            initial_scroll_top = driver.execute_script("return arguments[0].scrollTop", modal)
            
            print(f"容器初始滚动高度: {initial_scroll_height}")
            print(f"容器初始滚动位置: {initial_scroll_top}")
            
            # 执行滚动
            for i in range(5):
                print(f"执行第 {i+1} 次滚动...")
                
                # 模拟真实用户的滚动行为
                driver.execute_script("""
                    var modal = arguments[0];
                    var scrollStep = 200;
                    var scrolls = 0;
                    var maxScrolls = 10;
                    
                    function smoothScroll() {
                        modal.scrollTop += scrollStep;
                        scrolls++;
                        if (scrolls < maxScrolls && modal.scrollTop < modal.scrollHeight - modal.clientHeight) {
                            setTimeout(smoothScroll, 100);
                        }
                    }
                    
                    smoothScroll();
                """, modal)
                
                time.sleep(2)
                
                # 检查滚动位置变化
                current_scroll_top = driver.execute_script("return arguments[0].scrollTop", modal)
                current_scroll_height = driver.execute_script("return arguments[0].scrollHeight", modal)
                
                print(f"  当前滚动位置: {current_scroll_top}")
                print(f"  当前滚动高度: {current_scroll_height}")
                
                # 如果高度发生变化，说明有新内容加载
                if current_scroll_height > initial_scroll_height:
                    print(f"  ✅ 检测到内容高度增加: {current_scroll_height - initial_scroll_height}px")
                    initial_scroll_height = current_scroll_height
                
        except Exception as e:
            print(f"滚动操作失败: {e}")
        
        # 滚动后的分析
        print("\n📊 滚动后的DOM分析:")
        scrolled_analysis = analyze_dom_structure()
        
        # 比较结果
        print(f"\n🔍 对比分析结果:")
        print(f"不滚动时找到的Key Features部分: {len(initial_analysis)}")
        print(f"滚动后找到的Key Features部分: {len(scrolled_analysis)}")
        
        for i, (initial, scrolled) in enumerate(zip(initial_analysis, scrolled_analysis)):
            print(f"\n第{i+1}个Key Features部分:")
            print(f"  不滚动时特性数量: {initial['features_count']}")
            print(f"  滚动后特性数量: {scrolled['features_count']}")
            print(f"  特性数量变化: {scrolled['features_count'] - initial['features_count']}")
            
            if scrolled['features_count'] > initial['features_count']:
                print("  ✅ 滚动增加了Key Features数量！")
                new_features = scrolled['features'][initial['features_count']:]
                print("  新增的特性:")
                for j, feature in enumerate(new_features[:5]):
                    print(f"    +{j+1}. {feature}")
        
        # 保存分析结果
        result = {
            "initial_analysis": initial_analysis,
            "scrolled_analysis": scrolled_analysis,
            "scroll_effect_detected": any(s['features_count'] > i['features_count'] 
                                        for i, s in zip(initial_analysis, scrolled_analysis))
        }
        
        with open('./release/dom_analysis_result.json', 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
        
        print("\n💾 详细分析结果已保存到 ./release/dom_analysis_result.json")
        
    except Exception as e:
        print(f"❌ 分析过程中出现异常: {e}")
        import traceback
        traceback.print_exc()
        
    finally:
        print("🧹 清理资源...")
        driver.quit()

if __name__ == "__main__":
    analyze_key_features_dom()
